import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import Cookies from 'js-cookie'
import { login, register, getUserInfo } from '@/api/user'

export const useUserStore = defineStore('user', () => {
  const token = ref(Cookies.get('token') || '')
  const userInfo = ref(null)
  const isLoggedIn = computed(() => !!token.value)

  // 登录
  const loginUser = async (loginForm) => {
    try {
      const response = await login(loginForm)
      if (response.code === 200) {
        // 后端返回的token在data字段中
        token.value = response.data
        Cookies.set('token', token.value, { expires: 7 })
        // 登录成功后获取用户信息
        await fetchUserInfo()
        console.log('登录成功，token:', token.value)
        return { success: true }
      } else {
        return { success: false, message: response.message }
      }
    } catch (error) {
      console.error('登录失败:', error)
      return { success: false, message: '登录失败' }
    }
  }

  // 注册
  const registerUser = async (registerForm) => {
    try {
      const response = await register(registerForm)
      return response
    } catch (error) {
      return { success: false, message: '注册失败' }
    }
  }

  // 获取用户信息
  const fetchUserInfo = async () => {
    if (!token.value) return
    try {
      const response = await getUserInfo()
      if (response.code === 200) {
        userInfo.value = response.data
        console.log('获取用户信息成功:', userInfo.value)
      }
    } catch (error) {
      console.error('获取用户信息失败:', error)
      // 如果token无效，清除登录状态
      if (error.response?.status === 401) {
        logout()
      }
    }
  }

  // 登出
  const logout = () => {
    token.value = ''
    userInfo.value = null
    Cookies.remove('token')
  }

  // 初始化用户状态
  const initUserState = async () => {
    if (token.value && !userInfo.value) {
      await fetchUserInfo()
    }
  }

  return {
    token,
    userInfo,
    isLoggedIn,
    loginUser,
    registerUser,
    fetchUserInfo,
    logout,
    initUserState
  }
})